<template>
  <div class="app-container">
    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <user-edit :infoid="id" :read-only="readOnly" :timestamp="timestamp" @dialogHide="dialogHide($event)" />
    </el-dialog>

    <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="请输入关键词" style="width: 200px;margin-left: 10px;" class="filter-item" />
      <el-select v-model="listQuery.userType" placeholder="请选择用户类型" clearable style="margin-left: 10px;width: 200px" class="filter-item">
        <el-option label="全部" value="" />
        <el-option v-for="(it,index) in roleList" :key="index" :label="it.label" :value="it.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilter">
        搜索
      </el-button>
      <!-- <el-popconfirm v-if="roleEdit" title="确定批量删除所选信息吗？" style="margin-left:10px;float:right" @onConfirm="deleteData()">
        <el-button slot="reference" type="danger" class="filter-item" icon="el-icon-delete">批量删除</el-button>
      </el-popconfirm> -->
      <el-button v-if="roleEdit" class="filter-item" style="margin-left: 10px;float:right" type="success" icon="el-icon-edit" @click="addnew">
        新建
      </el-button>
    </div>

    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="roleEdit" type="selection" width="50" align="center" />

      <el-table-column align="center" prop="id" label="编号" width="280" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="150px" prop="user_name" label="用户名" align="left" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>

      <el-table-column width="150px" prop="user_type" label="用户类型" align="center" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ userTypeLabel(scope.row.userType) }}
        </template>
      </el-table-column>
      <el-table-column width="200px" prop="check_user_id" label="B网用户ID" align="center" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.checkUserId }}
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="user_enabled" width="90" align="center" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.enabled" type="success" effect="dark" style="cursor:pointer" title="停用用户" @click="setState(scope.row.id,false,scope.row.username)">正常</el-tag>
          <el-tag v-else type="info" effect="dark" style="cursor:pointer" title="启用用户" @click="setState(scope.row.id,true,scope.row.username)">停用</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button v-if="scope.row.enabled" type="primary" size="small" icon="el-icon-edit" @click="edit(scope.row.id)">
            编辑
          </el-button>
          <el-popconfirm v-if="scope.row.enabled" title="确定重置该用户密码为随机密码吗？" style="margin-left:10px;" @onConfirm="resetPassword(scope.row.id,scope.row.username)">
            <el-button slot="reference" type="warning" size="small" icon="el-icon-success">重置密码</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
// import { fetchList } from '@/api/article'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import userEdit from './edit'

export default {
  name: 'ArticleList',
  components: { Pagination, userEdit },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    isEdit: {
      type: Boolean,
      default: true
    },
    isSelection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleList: [{ value: 1, label: '车企' }, { value: 2, label: '检测机构' }, { value: 3, label: '管理员' }],
      roleEdit: true,
      selection: false,
      dicListLoading: false,
      stopDicLoading: false,
      startDicLoading: false,
      submitLoading: false,
      deptList: [],
      unitList: [],
      diclist: [],
      settingVisible: false,
      item: {},
      dialogtitle: '新增',
      dialogVisible: false,
      readOnly: false,
      timestamp: false,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        depitid: '',
        unitId: '',
        realName: '',
        page: 1,
        limit: 10
      },
      Sortkey: '',
      Isace: '',
      multipleSelection: [],
      id: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    userTypeLabel(id) {
      return this.roleList.find(item => item.value === id).label
    },
    setState(id, state, username) {
      if (this.roleEdit) {
        const stateText = state ? ' 启用用户 ' : ' 停用用户 '
        this.$confirm('确定要' + stateText + ' “' + username + '” 吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http
            .post('/api/user/updateEnabled', { id: id, userEnabled: state })
            .then(response => {
              if (response.data.success === true) {
                this.$message({
                  message: stateText + '成功',
                  type: 'success'
                })
                this.getList()
              } else {
                console.log(stateText + '失败:' + response.data.message)
                this.$message({
                  message: stateText + '失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已放弃' + stateText + '操作'
          })
        })
      }
    },
    resetPassword(id, username) {
      if (this.roleEdit) {
        this.$http
          .get('/api/user/resetPassword?userId=' + id)
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                showClose: true,
                duration: 0,
                message: '重置密码成功，用户 ' + username + ' 的新密码为：' + response.data.result + '，请注意保存',
                type: 'success'
              })
            } else {
              console.log('重置密码失败:' + response.data.message)
              this.$message({
                message: '重置密码失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteData(id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      if (ids.length > 0) {
        this.$http
          .post('/api/user/removeUser', { ids: ids })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('删除失败:' + response.data.message)
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    addnew() {
      this.id = 0
      this.readOnly = false
      this.dialogtitle = '新增'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    edit(id) {
      this.id = id
      this.readOnly = false
      this.dialogtitle = '编辑'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    detail(id) {
      this.id = id
      this.readOnly = true
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    dialogHide(flag) {
      this.dialogVisible = false
      this.getList()
    },
    getList() {
      const para = {
        username: this.listQuery.username,
        userType: this.listQuery.userType,
        orderField: this.Sortkey,
        orderType: this.Isace,
        pageNum: this.listQuery.page,
        pageSize: this.listQuery.limit
      }
      this.listLoading = true
      this.$http
        .post('/api/user/queryByPage', para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result.records
            this.total = response.data.result.total
            if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
              this.listQuery.page = response.data.result.pages
              this.getList()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   this.listLoading = false
      // })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
